package top.zerozoo.learn.grade.servlet;

import org.apache.commons.beanutils.BeanUtils;
import top.zerozoo.learn.grade.factory.ServiceFactory;
import top.zerozoo.learn.grade.service.MajorService;
import top.zerozoo.learn.grade.service.StudentService;
import top.zerozoo.learn.grade.util.NumberUtils;
import top.zerozoo.learn.grade.vo.StudentEditInfo;
import top.zerozoo.learn.grade.vo.StudentInfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebServlet("/studentEdit.do")

public class StudentEditServlet extends HttpServlet {
    private final StudentService studentService = ServiceFactory.get(StudentService.class);
    private final MajorService majorService = ServiceFactory.get(MajorService.class);

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String, String[]> parameterMap = req.getParameterMap();
        StudentEditInfo workerEditInfo = new StudentEditInfo();
        try {
            BeanUtils.populate(workerEditInfo, parameterMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        final int id = NumberUtils.parse(workerEditInfo.getId(), Integer.class, -1);
        if (id <= 0) {
            req.setAttribute("error_msg", "未提供要编辑的学生ID！");
            req.getRequestDispatcher("/studentEdit.jsp").forward(req, resp);
            return;
        }
        if(!"submit".equalsIgnoreCase(workerEditInfo.getAction())){
            StudentInfo studentInfo = studentService.find(id);
            req.setAttribute("studentInfo", studentInfo);
            req.setAttribute("majors", majorService.findAll());
            req.getRequestDispatcher("/studentEdit.jsp").forward(req, resp);
            System.out.println(studentInfo);
            return;
        }
        studentService.update(workerEditInfo.toWorker());
        resp.sendRedirect(req.getContextPath()+"studentDetail.do?id="+workerEditInfo.getId());
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
